<template>
  <ul class="stack">
    <li
      class="stack-item"
      v-for="(item, index) in pages"
      :key="index"
      @touchmove.stop="touchmove"
      @touchstart="touchstart"
      @touchend="touchend"
      :style="calcStyle"
    >
      <total-count-card
        :data="data"
        @changeTotalScore="changeTotalScore"
        @clickScore="clickScore"
        :scores="scores"
      ></total-count-card>
    </li>
  </ul>
</template>
<script>
import totalCountCard from "./totalCountCard";
export default {
  props: {
    // pages数据包含基础的图片数据
    pages: {
      type: Array,
      default: [1]
    },
    scores: {
      type: Object,
      default: {}
    },
    data: {
      type: Object
    }
  },
  components: {
    totalCountCard
  },
  data() {
    return {
      // basicdata数据包含组件基本数据
      basicdata: {
        start: {}, // 记录起始位置
        end: {}, // 记录终点位置
        currentPage: 0 // 默认首图的序列
      },
      // temporaryData数据包含组件临时数据
      temporaryData: {
        poswidth: "", // 记录位移
        posheight: "", // 记录位移
        tracking: false, // 是否在滑动，防止多次操作，影响体验
        animation: false, // 首图是否启用动画效果，默认为否
        opacity: 1 // 记录首图透明度
      }
    };
  },
  methods: {
    changeTotalScore(val) {
      this.$emit("changeTotalScore", val);
    },
    validateData() {
      if (!this.data.needScore) {
        return true;
      }
      let flag = true;
      const keys = Object.keys(this.scores);
      keys.some(key => {
        if (!this.scores[key]) {
          flag = false;
          return true;
        }
      })
      return flag;
    },
    clickScore(type) {
      this.$emit("clickScore", type);
    },
    touchstart(e) {
      e = e.mp;
      if (this.temporaryData.tracking) {
        return;
      }
      // 是否为touch
      if (e.type === "touchstart") {
        if (e.touches.length > 1) {
          this.temporaryData.tracking = false;
          return;
        } else {
          // 记录起始位置
          this.basicdata.start.t = new Date().getTime();
          this.basicdata.start.x = e.touches[0].clientX;
          this.basicdata.start.y = e.touches[0].clientY;
          this.basicdata.end.x = e.touches[0].clientX;
          this.basicdata.end.y = e.touches[0].clientY;
        }
        // pc操作
      } else {
        this.basicdata.start.t = new Date().getTime();
        this.basicdata.start.x = e.clientX;
        this.basicdata.start.y = e.clientY;
        this.basicdata.end.x = e.clientX;
        this.basicdata.end.y = e.clientY;
      }
      this.temporaryData.tracking = true;
      this.temporaryData.animation = false;
    },
    touchmove(e) {
      e = e.mp;
      // 记录滑动位置
      if (this.temporaryData.tracking && !this.temporaryData.animation) {
        if (e.type === "touchmove") {
          this.basicdata.end.x = e.touches[0].clientX;
          this.basicdata.end.y = e.touches[0].clientY;
        } else {
          this.basicdata.end.x = e.clientX;
          this.basicdata.end.y = e.clientY;
        }
        // 计算滑动值
        this.temporaryData.poswidth =
          this.basicdata.end.x - this.basicdata.start.x;
        this.temporaryData.posheight =
          this.basicdata.end.y - this.basicdata.start.y;
      }
    },
    touchend(e) {
      e = e.mp;
      this.temporaryData.tracking = false;
      this.temporaryData.animation = true;
      const reset = () => {
        this.temporaryData.poswidth = 0;
        this.temporaryData.posheight = 0;
      };
      const swiperOut = () => {
        // 最终位移简单设定为x轴200像素的偏移
        let ratio = Math.abs(
          this.temporaryData.posheight / this.temporaryData.poswidth
        );
        this.temporaryData.poswidth =
          this.temporaryData.poswidth >= 0
            ? this.temporaryData.poswidth + 200
            : this.temporaryData.poswidth - 200;
        this.temporaryData.posheight =
          this.temporaryData.posheight >= 0
            ? Math.abs(this.temporaryData.poswidth * ratio)
            : -Math.abs(this.temporaryData.poswidth * ratio);
        this.temporaryData.opacity = 0;
      };
      // 滑动结束，触发判断
      // 简单判断滑动宽度超出100像素时触发滑出

      if (
        Math.abs(this.temporaryData.poswidth) >= 100 ||
        -this.temporaryData.posheight >= 100
      ) {
        if (!this.validateData()) {
          reset();
          return;
        }
        swiperOut();
        this.$emit("commit");
        // 不满足条件则滑入
      } else if (this.temporaryData.posheight >= 100) {
        this.$emit("cancel");
        swiperOut();
      } else {
        reset();
      }
    },
    // 非首页样式切换
    transform(index) {
      if (index > this.basicdata.currentPage) {
        let style = {};
        let visible = 3;
        let perIndex = index - this.basicdata.currentPage;
        // visible可见数量前滑块的样式
        if (index <= this.basicdata.currentPage + visible - 1) {
          style["opacity"] = "1";
          style["transform"] =
            "translate3D(0,0," + -1 * perIndex * 60 + "px" + ")";
          style["zIndex"] = visible - index + this.basicdata.currentPage;
          style["transitionTimingFunction"] = "ease";
          style["transitionDuration"] = 300 + "ms";
        } else {
          style["zIndex"] = "-1";
          style["transform"] =
            "translate3D(0,0," + -1 * visible * 60 + "px" + ")";
        }
        return style;
      }
    },
    // 首页样式切换
    transformIndex(index) {
      let str = "";
      // 处理3D效果
      if (index === this.basicdata.currentPage) {
        let style = {};
        style["transform"] =
          "translate3D(" +
          this.temporaryData.poswidth +
          "px" +
          "," +
          this.temporaryData.posheight +
          "px" +
          ",0px)";
        style["opacity"] = this.temporaryData.opacity;
        style["z-index"] = 10;
        if (this.temporaryData.animation) {
          style["transition-timing-function"] = "ease";
          style["transition-duration"] = 300 + "ms";
        }
        Object.keys(style).forEach(key => {
          if (style[key] === "translate3D(px,px,0px)") return;
          str += `${key}:${style[key]};`;
        });
        return str;
      }
    }
  },
  computed: {
    calcStyle() {
      return this.transformIndex(0);
    }
  }
};
</script>

<style>
.stack {
  width: 100%;
  height: 100%;
  position: relative;
  perspective: 1000px;
  perspective-origin: 50% 150%;
  -webkit-perspective: 1000px;
  -webkit-perspective-origin: 50% 150%;
  margin: 0;
  padding: 0;
}
.stack-item {
  height: 100%;
  width: 100%;
  border-radius: 4px;
  text-align: center;
  position: absolute;
  opacity: 0;
  display: flex;
  flex-direction: column;
  user-select: none;
  pointer-events: auto;
}
.stack-container li.move-back {
  /* http://matthewlein.com/ceaser/ */
  -webkit-transition-timing-function: cubic-bezier(
    0.175,
    0.885,
    0.47,
    1
  ); /* older webkit */
  -webkit-transition-timing-function: cubic-bezier(0.175, 0.885, 0.47, 1.515);
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.47, 1.515);
}
</style>